package com.gkc.trx.controller;

import com.gkc.trx.core.ApiWrapper;
import com.gkc.trx.core.contract.Contract;
import com.gkc.trx.core.contract.Trc20Contract;
import com.gkc.trx.core.exceptions.IllegalException;
import com.gkc.trx.proto.Chain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;
import java.util.List;

@RestController
@RequestMapping("/trx")
public class TrxController {
    @Value("${trx.owner-address}")
    private String ownerAddress;//主钱包地址
    @Value("${trx.private-key}")
    private String privateKey;//主钱包地址私钥
    @Value("${trx.contract-address}")
    private String contractAddress;//合约地址

    //trx转账
    @GetMapping("/transferTrx")
    public String transferTrx(String toAddress, long amount) throws IllegalException {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);
        //交易
        com.gkc.trx.proto.Response.TransactionExtention result = client.transfer(ownerAddress, toAddress, amount);
        //签名
        Chain.Transaction signedTransaction = client.signTransaction(result);
        //广播交易
        String txId = client.broadcastTransaction(signedTransaction);
        return txId;
    }

    //合约转账
    @GetMapping("/transferContract")
    public String transfer(String toAddress, long amount) {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);
        Contract contract = client.getContract(contractAddress);
        Trc20Contract token = new Trc20Contract(contract, ownerAddress, client);
        String txid = token.transfer(toAddress, amount, "memo", 1000000000L);
        return txid;
    }
    //生成地址
    @GetMapping("/generateAddress")
    public List<String> generateAddress() {
        return ApiWrapper.generateAddress();
    }

    //获取trc20代币余额
    @GetMapping("/getBalance")
    public String getAccount(String address) {
        ApiWrapper client = ApiWrapper.ofNile(privateKey);//需要查询的用户的私钥，可以自己改
        Contract contract = client.getContract(contractAddress);
        Trc20Contract token = new Trc20Contract(contract, contractAddress, client);
        BigInteger balance = token.balanceOf(address);
        return balance.toString();
    }


}
